package com.mikey.mikeyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.mikey.mikeyojcodesandbox.model.ExecuteCodeRequest;
import com.mikey.mikeyojcodesandbox.model.JudgeInfo;
import com.mikey.mikeyojcodesandbox.model.ExecuteCodeResponse;
import com.mikey.mikeyojcodesandbox.model.ExecuteMessage;
import com.mikey.mikeyojcodesandbox.utils.ProcessUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class JavaNativeCodeSandboxOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";



    /**
     * 测试沙箱方法
     * @param args
     */
    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaCodeSandbox =new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2","3 4"));
        String code = ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCodeInteraction/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);

    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

//        System.setSecurityManager(new DenySecurityManager());
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 1、把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        // File.separator是为了兼容不同操作系统
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;

        // 判断全局代码目录是否存在，不存在则新建
        if (!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }

        // 用户存放的代码进行隔离
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        System.out.println(userCodeFile.getAbsolutePath());
        // 2、编译代码得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        ExecuteMessage compileMessage = ProcessUtils.getProcessMessage(compileCmd,"编译");
        System.out.println(compileMessage);

        // 3、运行代码得到输出结果
        List<ExecuteMessage> executeMessages = new ArrayList<>();
        for (String inputArgs : inputList){
            // 需要限制运行代码需要的最大内存
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            ExecuteMessage runMessage = ProcessUtils.getProcessMessage(runCmd,"运行");
//                Process compileProcess = Runtime.getRuntime().exec(runCmd);
//                ExecuteMessage compileMessage = ProcessUtils.getInterActionProcessMessage(compileProcess,"运行",inputArgs);
            System.out.println(runMessage);
            executeMessages.add(runMessage);
        }

        // 4、收集整理的输出结果
        // 判断运行时间是否超时
        long maxTime = 0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessages){
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                // 表示运行错误，比如程序运行失败的信息
                executeCodeResponse.setStatus("3");
                break;
            }
            long time = executeMessage.getTime();
            if (time > maxTime){
                maxTime = time;
            }
            // 正常运行完成
            executeCodeResponse.setStatus("1");
            // 6、错误处理，提成程序的健壮性
            if (executeMessage.getStatus() != null && executeMessage.getStatus() == 2){
                // 沙箱错误，可能是编译出现错误
                executeCodeResponse.setStatus("2");
            }

            outputList.add(executeMessage.getMessage());
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        // 获取最大运行时间
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5、删除临时文件
        if (userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除"+(del?"成功":"失败"));
        }

        return executeCodeResponse;
    }


}
